package com.littlebee.storychild.common.http;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.littlebee.storychild.common.BaseResponse;
import com.littlebee.storychild.common.BaseResutlResponse;
import com.littlebee.storychild.common.json.JsonTools;
import com.littlebee.storychild.common.utils.LogUtil;
import com.zss.library.utils.LogUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 作者：liaoyong on 2016/7/14 16:45
 * 邮箱：liaoyong@tuliu.com
 * 描述：http工具类
 */
public class HttpHelper {
    private Context ctx;

    private static HttpHelper instance = null;

    private HttpHelper(Context ctx) {
        this.ctx = ctx;
    }

    public static HttpHelper getInstance(Context ctx) {
        if (instance == null) {
            instance = new HttpHelper(ctx);
        }
        return instance;
    }


    /*
    * 新重构追加方法
    * 网络请求接口：
    * 返回data为jsonObject时，调用此方法，传入class名称，会自动解析
    * @param requestCode 请求tag
    * @param url 请求的url
    * @param hashMap
    * @param genericType 泛型
    * @param isArrayData 返回的data数据是否array
    * @param httpCallback
    * */
    public <T> T doRequest(final int requestCode, String url, HashMap<String, Object> hashMap,
                           final Class<T> genericType, final boolean isArrayData, final HttpCallback httpCallback) {
        //Post参数
        if (hashMap != null) {
            url = String.format("%s?", url);
            Iterator iter = hashMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = (String) entry.getKey();
                Object val = entry.getValue();
                try {
                    val = URLEncoder.encode(val.toString(),"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                url = String.format("%s%s=%s&", url, key, val);
            }
        }
        LogUtil.d("request url:" + url);
        BaseRequest request = new BaseRequest(BaseRequest.Method.GET ,url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String responseString = "";
                        try {
                            responseString = URLDecoder.decode(response.toString(),"UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                        LogUtil.d("http response:" + responseString);
                        //目前json不是太规范，还不能用gson
                        //parse json,step1:parse code;step2:parse data to String
                        BaseResutlResponse baseResutlResponse = null;
                        try {
                            baseResutlResponse = JsonTools.jsonParseCollection
                                    (new JSONObject(response), BaseResutlResponse.class);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (baseResutlResponse == null) {
                            httpCallback.onFailure(requestCode, "接口返回数据异常");
                            return;
                        }
                        BaseResponse baseResponse = baseResutlResponse.getResult();
                        if (baseResponse.getCode() == ResultCode.CODE_SUCCESS) {
                            String data = baseResutlResponse.getResponse() == null ? "" : baseResutlResponse.getResponse();
                            Object object = parseJsonObjectData(requestCode, data, genericType, isArrayData);
                            httpCallback.onSuccess(requestCode, object, baseResponse.getPagination(), baseResponse.getMsg());
                        } else if (baseResponse.getCode() == ResultCode.TOKEN_CHANGE || baseResponse.getCode() == ResultCode.TOKEN_INVALID) {
                            //token失效会跳转到登录界面
                        } else {
                            httpCallback.onFailure(requestCode, baseResponse.getMsg());
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (error.networkResponse == null) {
                            httpCallback.onFailure(500, "网络错误，请检查你的网络情况");
                        } else {
                            httpCallback.onFailure(error.networkResponse.statusCode, "网络错误，请检查你的网络情况");
                        }
                    }
                }
        );
        //Post参数
//        if (hashMap != null) {
//            Iterator iter = hashMap.entrySet().iterator();
//            while (iter.hasNext()) {
//                Map.Entry entry = (Map.Entry) iter.next();
//                String key = (String) entry.getKey();
//                Object val = entry.getValue();
//                request.setParam(key, String.valueOf(val));
//            }
//        }

        RequestQueueHelper.getInstance(ctx).add(request);
        return null;
    }


    /*
  * 新重构追加方法
  * 网络请求接口：
  * 返回data为jsonObject时，调用此方法，传入class名称，会自动解析
  * @param requestCode 请求tag
  * @param url 请求的url
  * @param hashMap
  * @param genericType 泛型
  * @param isArrayData 返回的data数据是否array
  * @param httpCallback
  * */
    public <T> T doPostRequest(final int requestCode, String url, HashMap<String, Object> hashMap,
                               final Class<T> genericType, final boolean isArrayData, final HttpCallback httpCallback) {
        //Post参数
        LogUtil.d("request url:" + url);
        BaseRequest request = new BaseRequest(BaseRequest.Method.POST ,url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String responseString = "";
                        try {
                            responseString = URLDecoder.decode(response.toString(),"UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                        LogUtil.d("http response:" + responseString);
                        //目前json不是太规范，还不能用gson
                        //parse json,step1:parse code;step2:parse data to String
                        BaseResutlResponse baseResutlResponse = null;
                        try {
                            baseResutlResponse = JsonTools.jsonParseCollection
                                    (new JSONObject(response), BaseResutlResponse.class);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (baseResutlResponse == null) {
                            httpCallback.onFailure(requestCode, "接口返回数据异常");
                            return;
                        }
                        BaseResponse baseResponse = baseResutlResponse.getResult();
                        if (baseResponse.getCode() == ResultCode.CODE_SUCCESS) {
                            String data = baseResutlResponse.getResponse() == null ? "" : baseResutlResponse.getResponse();
                            LogUtils.i("XHX","XHX返回数据："+data);
                            Object object = parseJsonObjectData(requestCode, data, genericType, isArrayData);
                            httpCallback.onSuccess(requestCode, object, baseResponse.getPagination(), baseResponse.getMsg());
                        } else if (baseResponse.getCode() == ResultCode.TOKEN_CHANGE || baseResponse.getCode() == ResultCode.TOKEN_INVALID) {
                            //token失效会跳转到登录界面
                        } else {
                            httpCallback.onFailure(requestCode, baseResponse.getMsg());
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (error.networkResponse == null) {
                            httpCallback.onFailure(500, "网络错误，请检查你的网络情况");
                        } else {
                            httpCallback.onFailure(error.networkResponse.statusCode, "网络错误，请检查你的网络情况");
                        }
                    }
                }
        );
        //Post参数
        if (hashMap != null) {
            Iterator iter = hashMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = (String) entry.getKey();
                Object val = entry.getValue();
                request.setParam(key, String.valueOf(val));
            }
        }
        RequestQueueHelper.getInstance(ctx).add(request);
        return null;
    }
    /**
     * 检测网络是否可用
     *
     * @return
     */
    public boolean isNetworkAvailable() {
        ConnectivityManager connectivity = (ConnectivityManager)
                ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.getState() == NetworkInfo.State.CONNECTED) {
                return true;
            }
        }
        return false;
    }

    private <T> T parseJsonObjectData(int vocationalId, Object data, Class<T> genericType, boolean isArrayData) {
        if (data == null || TextUtils.isEmpty(data.toString()))
            return null;

        if (isArrayData == true) {
            //数组解析
            try {
                List<T> listObj = null;
                listObj = JsonTools.jsonParseCollection(new JSONArray(data.toString()), genericType);
                return (T) listObj;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            T object = null;
            try {
                object = JsonTools.jsonParseCollection(new JSONObject(data.toString()), genericType);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return object;
        }
        return null;
    }

    public static String toURLEncoded(String paramString) {
        if (paramString == null || paramString.equals("")) {
            LogUtil.d("toURLEncoded error:"+paramString);
            return "";
        }

        try
        {
            String str = new String(paramString.getBytes(), "UTF-8");
            str = URLEncoder.encode(str, "UTF-8");
            return str;
        }
        catch (Exception localException)
        {
            LogUtil.e("toURLEncoded error:"+paramString);
        }

        return "";
    }
}
